package com.tool4j.util.http;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class IPUtil {

    private static final List<String> IP_HEADERS = Arrays.asList(
            "x-forwarded-for",//Squid 服务代理
            "X-Real-IP",//nginx服务代理
            "Proxy-Client-IP",//apache 服务代理
            "HTTP_CLIENT_IP",//一些代理服务器
            "WL-Proxy-Client-IP",//weblogic 服务代理
            "HTTP_X_FORWARDED_FOR"
    );

    private static Searcher searcher;

    @Value("${ipdb.path}")
    private String path;

    /**
     * 获取IP地址
     *
     * @param request
     * @return
     */
    public String getIp(ServerHttpRequest request) {
        String ip = null;
        for (String key : IP_HEADERS) {
            if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
                break;
            }
            ip = request.getHeaders().get(key) != null ? request.getHeaders().get(key).toString() : null;
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress() != null ?
                    request.getRemoteAddress().getAddress().getHostAddress()
                    : request.getLocalAddress() != null
                    ? request.getLocalAddress().getAddress().getHostAddress()
                    : "unknow";
        }
        if (ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        if (ip.startsWith("[") && ip.endsWith("]")) {
            ip = ip.substring(1, ip.length() - 1);
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    /**
     * 查询ip归属地
     *
     * @param ip
     * @return
     */
    public String searchRegion(String ip) {
        if (StrUtil.isBlank(ip)) {
            return null;
        }
        try {
            if (searcher == null) {
                searcher = Searcher.newWithFileOnly(path);
            }
            String region = searcher.search(ip);
            return StrUtil.isNotBlank(region) ? region : "未知";
        } catch (Exception e) {
        }
        return null;
    }
}
